//管理员对程序授权
"use strict"

const mvc   = require('cosjs.mvc');
const dbase = require('../dbase');

class authorize extends dbase.mongodb {
    constructor(){
        super('authorize');
    }
    get(uid,branch){
        let _id = ObjectID(uid,branch);
        return super.get(_id,'level');
    }
    set(id,data){
        let query = {"_id":ObjectID(data.uid,data.branch)};
        let update = {"$set":data};
        let option = {"multi":false};
        update["$setOnInsert"] = {"_id":ObjectID(data.uid,data.branch)};
        return this.update(query,update,option);
    }

    mget(uid){
       // let keys = ['branch','op','dev'];
        let query = {"uid":uid};
        let option = {"multi":true,"key":"branch"};
        return this.find(query,option)
    }
    insert(args){
        args._id=ObjectID(args.uid,args.branch);
        return super.insert(args);
    }


    //获取用户应用列表
    branch(uid,level) {
        return Promise.resolve(level).then(ret=>{
            if(level>=100){
                return null;
            }
            return this.mget(uid).then(ret=>ret?Object.keys(ret):[]);
        }).then(id=>{
            if(id && id.length === 0){
                return null;
            }
            let keys = arguments[2]||['name'];
            let branch = mvc.model.admin("branch");
            return branch.get(id,keys);
        })
    }

    //获得用户列表
    async branchNew(uid){
        let id=null;     
        let keys = ['branch','op','dev'];
        let query = {"uid":uid};
        let option = {"multi":true,"fields":this.fields(keys),"key":"branch"};
        let ret=await this.find(query,option);
        if(ret){
            let bname_list=Object.keys(ret);
            let keys = arguments[2]||['name'];
            let branch = mvc.model.admin("branch");
            let bret=await branch.get(bname_list,keys);
            for(let k in ret){
                ret[k]['name']=bret[k]['name'];
            }
            return ret;
        }
        else{
            return [];
        }
    }
}



function ObjectID(id){
    if(id.indexOf('-')>0){
        return id;
    }
    else{
        return Array.from(arguments).join('-');
    }
}

module.exports =  function(){
    return new authorize();
}


